/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ftpcombiner.gui.applicationframe.framesplitter.filetree;

import ftpcombiner.filesystem.FileSystem;
import ftpcombiner.server.virtualfiles.VirtualFile;
import ftpcombiner.server.virtualfiles.VirtualFolder;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Ben
 */
public class FileTreeModel implements TreeModel {

    EventListenerList listenerList = new EventListenerList();
//
//    public FileTreeModel() {
//        super(FileSystem.getInstance().getRootDir(), true);
//    }
//    

    @Override
    public Object getRoot() {
        return FileSystem.getInstance().getRootDir();
    }

    @Override
    public Object getChild(Object parent, int index) {
        Object o = ((VirtualFolder) parent).getChildAt(index);

        if (o == null) {
            o = "Loading...";
//            System.out.println(((VirtualItem) parent).getPath());
//            String path = FileSystem.getInstance().getCurrentDir().getPath();
//            FileSystem.getInstance().changeDirectory(((VirtualItem) parent).getPath(), false, null);
//            FileSystem.getInstance().changeDirectory(path);
//            System.out.println("path: " + path + " curDir: " + FileSystem.getInstance().getCurrentDir().getPath());
        }
        return o;
    }

    @Override
    public int getChildCount(Object parent) {
        return ((VirtualFolder) parent).getChildren() == null ? 1 : ((VirtualFolder) parent).getChildCount();
    }

    @Override
    public boolean isLeaf(Object node) {
        return node instanceof VirtualFile || node instanceof String;
    }

    @Override
    public void valueForPathChanged(TreePath path, Object newValue) {
        for (TreeModelListener l : ((TreeModelListener[]) listenerList.getListenerList())) {
            l.treeNodesChanged(new TreeModelEvent(this, path));
        }
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        return ((VirtualFolder) parent).getIndex((TreeNode) child);
    }

    @Override
    public void addTreeModelListener(TreeModelListener l) {
        listenerList.add(TreeModelListener.class, l);
    }

    @Override
    public void removeTreeModelListener(TreeModelListener l) {
        listenerList.remove(TreeModelListener.class, l);
    }

    public void fireTreeNodeLoaded(TreePath path) {
        for (TreeModelListener l : listenerList.getListeners(TreeModelListener.class)) {
            l.treeNodesInserted(new TreeModelEvent(this, path));
        }
        
    }
}